package com.example.weiwing;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.icu.util.Calendar;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bumptech.glide.Glide;

import com.example.weiwing.config.WeiWingConfig;
import com.example.weiwing.entity.User;
import com.example.weiwing.util.ChooseVideoOrPictureUtils;
import com.example.weiwing.util.CircleImageView;
import com.example.weiwing.util.SpUtils;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.XXPermissions;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.JsonMap;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.List;

public class EditProfileActivity extends AppCompatActivity {
    private EditText editTextBirthday;
    private Button btn_sava;
    private EditText et_nickName;
    private EditText et_signature;
    private CircleImageView iv_avatar;
    private String mSelectType;
    private String imagePath;

    private boolean imageChange = false;

    private User user;
    private RadioButton rb_male;
    private RadioButton rb_female;

    private Handler mHandler;
    private String nickName;
    private String signature;
    private String gender;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);
        user = (User) getIntent().getBundleExtra("data").get("user");
        iv_avatar = findViewById(R.id.imageViewProfile);
        et_nickName = findViewById(R.id.editTextNickname);
        et_signature = findViewById(R.id.editTextSignature);
        rb_male = findViewById(R.id.radioButtonMale);
        rb_female = findViewById(R.id.radioButtonFemale);
        btn_sava = findViewById(R.id.buttonSave);

        Glide.with(EditProfileActivity.this).load(WeiWingConfig.getUrl() + user.getAvatar()).into(iv_avatar);
        et_nickName.setText(user.getNickName());
        et_signature.setText(user.getSignature());
        imagePath = WeiWingConfig.getUrl() + user.getAvatar();

        if (user.getGender().equals("0")) {
            rb_male.setChecked(true);
            rb_female.setChecked(false);
        } else {
            rb_male.setChecked(false);
            rb_female.setChecked(true);
        }

        mHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 1) {
                    JsonMap jsonMap = new JsonMap();
                    jsonMap.set("userId", user.getUserId());
                    jsonMap.set("nickName", nickName);
                    jsonMap.set("signature", signature);
                    jsonMap.set("gender", gender);
                    new Thread(() -> HttpRequest.build(EditProfileActivity.this, WeiWingConfig.getUrl() + "/user/profile/info")
                            .addHeaders("token", SpUtils.getString(EditProfileActivity.this, "token"))
                            .setJsonParameter(jsonMap)
                            .setResponseListener(new ResponseListener() {
                                @Override
                                public void onResponse(String response, Exception error) {
                                    if (error == null) {
                                        JSONObject jsonObject = JSON.parseObject(response);
                                        if (jsonObject.getInteger("code") == 200) {
                                            mHandler.obtainMessage(2).sendToTarget();
                                        } else {

                                        }

                                    } else {
                                        Toast.makeText(EditProfileActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }).doPut()).start();
                } else if (msg.what == 2) {

                    //数据是使用Intent返回
                    Intent intent = new Intent();
                    //设置返回数据
                    EditProfileActivity.this.setResult(RESULT_OK, intent);
                    //关闭Activity
                    EditProfileActivity.this.finish();

                }
            }
        };

        iv_avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                choosePicture();
            }
        });

        btn_sava.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户输入的信息
                nickName = et_nickName.getText().toString();
                signature = et_signature.getText().toString();
                gender = rb_male.isChecked() ? "0" : "1";

                if (TextUtils.isEmpty(nickName)) {
                    Toast.makeText(EditProfileActivity.this, "昵称不得为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(signature)) {
                    Toast.makeText(EditProfileActivity.this, "昵称不得为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (imageChange) {
                    new Thread(() -> HttpRequest.build(EditProfileActivity.this, WeiWingConfig.getUrl() + "/user/profile/avatar")
                            .addHeaders("token", SpUtils.getString(EditProfileActivity.this, "token"))
                            .addParameter("avatarfile", new File(imagePath))
                            .setResponseListener(new ResponseListener() {
                                @Override
                                public void onResponse(String response, Exception error) {
                                    if (error == null) {
                                        JSONObject jsonObject = JSON.parseObject(response);
                                        if (jsonObject.getInteger("code") == 200) {
                                            imagePath = jsonObject.getString("imgUrl");
                                            mHandler.obtainMessage(1).sendToTarget();
                                        } else {

                                        }

                                    } else {
                                        Toast.makeText(EditProfileActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }).doPost()).start();
                } else {
                    mHandler.obtainMessage(1).sendToTarget();
                }


            }
        });

//        Button pickDateButton = findViewById(R.id.buttonPickDate);
//        editTextBirthday = findViewById(R.id.editTextBirthday);

//        pickDateButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showDatePickerDialog();
//            }
//        });
    }

    private void choosePicture() {
        XXPermissions.with(this)
                .permission(android.Manifest.permission.CAMERA, android.Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> list, boolean b) {
                        //选择视频
                        mSelectType = "image";
                        ChooseVideoOrPictureUtils.PictureShoot(EditProfileActivity.this);
                    }

                    @Override
                    public void noPermission(List<String> list, boolean b) {
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST && resultCode == RESULT_OK) {
            if ("image".equals(mSelectType)) {
                List<LocalMedia> mLocalImageVideo = PictureSelector.obtainMultipleResult(data);
                if (!TextUtils.isEmpty(mLocalImageVideo.get(0).getCutPath())) {
                    imagePath = mLocalImageVideo.get(0).getCutPath();
                } else {
                    imagePath = mLocalImageVideo.get(0).getRealPath();
                }

                if (!TextUtils.isEmpty(imagePath)) {
                    //显示头像
                    Glide.with(EditProfileActivity.this).load(imagePath).into(iv_avatar);
                    imageChange = true;
                } else {
                    Toast.makeText(this, "获取头像失败", Toast.LENGTH_SHORT).show();
                }

                return;
            }
        }
    }


    private void showDatePickerDialog() {
        DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                // 在用户选择日期时自动填写生日一栏
                String selectedDate = year + "-" + (month + 1) + "-" + dayOfMonth;
                editTextBirthday.setText(selectedDate);
            }
        };

        // 获取当前日期
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        // 创建日期选择器对话框
        DatePickerDialog datePickerDialog = new DatePickerDialog(EditProfileActivity.this, dateSetListener, year, month, day);
        datePickerDialog.show();
    }
}